package com.sloth.controller;

import com.sloth.pojo.*;
import com.sloth.rabbitmq.MQSender;
import com.sloth.service.SeckillService;
import com.sloth.util.JsonUtil;
import com.sloth.util.ServerResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class SeckillController implements InitializingBean {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MQSender mqSender;

    @Autowired
    private RedisScript<Long> script;



    private Map<Integer,Boolean> EmptyStockMap = new HashMap<>();

    @GetMapping("/seckill")
    @ResponseBody
    public ServerResponse getSeckill(@RequestParam("starttime") String starttime) {
        System.out.println("开始时间: " + starttime);

        return seckillService.getSeckillProduct(starttime);
    }



    @GetMapping("/testsec")
    @ResponseBody
    public ServerResponse getSec(@RequestParam("secId") int secId, @RequestParam("addressId") int addressId,Customer customer) {

        // 1. 判断登录
        if (customer==null){
            return ServerResponse.saveFail("请登录");
        }
        int custId =customer.getCustId();

        ServerResponse serverResponse = null;

//        SeckillList seckill = seckillService.getSeckill(secId);


        ValueOperations valueOperations = redisTemplate.opsForValue();

        // 2. 判断是否重复抢购
        Myorder seckillOrder = (Myorder) redisTemplate.opsForValue().get("order:" + custId + ":" + secId);
        if (seckillOrder != null) {
            serverResponse = ServerResponse.saveFail("重复抢购");
            return serverResponse;
//            mav.addObject("message", serverResponse);
//            mav.setViewName("test/test");
//            return mav;
        }


        // 3. 判断map中是库存否是false (false为未售空, true为售空)
        if(EmptyStockMap.get(secId)){
            serverResponse = ServerResponse.saveFail("库存不足");
            return serverResponse;

//            mav.addObject("message", serverResponse);
//            mav.setViewName("test/test");
//            return mav;
        }


//        Long stock = valueOperations.decrement("seckill:"+secId);

        // 4. 预减库存
        Long stock = (Long) redisTemplate.execute(script, Collections.singletonList("seckill:"+secId),Collections.EMPTY_LIST);

        if (stock<0){
            EmptyStockMap.put(secId,true);
            valueOperations.increment("seckill:"+secId);
            serverResponse = ServerResponse.saveFail("库存不足");
            return serverResponse;


//            mav.addObject("message", serverResponse);
//            mav.setViewName("test/test");
//            return mav;
        }


        // 秒杀-减库存-创建订单
//        serverResponse = seckillService.seckill(secId,custId);

        SeckillMessage seckillMessage = new SeckillMessage(custId,secId,addressId);
        mqSender.sendSeckillMessage(JsonUtil.object2Jsonstr(seckillMessage));

        serverResponse = ServerResponse.saveSuccess("订单秒杀中");
        return serverResponse;

//        mav.addObject("message", serverResponse);
//        mav.setViewName("test/test");
//        return mav;

    }


    /**
     * x系统初始化,把商品库存数量加到Redis
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<SeckillList> list = seckillService.getAllSeckill();
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(seckill -> {
            redisTemplate.opsForValue().set("seckill:"+seckill.getSecId(),seckill.getSecStock());
            EmptyStockMap.put(seckill.getSecId(),false);
        });

    }


    /**
     *
     * 获取秒杀结果
     * @param customer
     * @param secId
     * @return secOrderId: 成功,  -1: 秒杀失败 , 0: 排队中
     */
    @GetMapping("getSecRresult")
    @ResponseBody
    public ServerResponse getResult(@RequestParam("secId")int secId,Customer customer){

        if (customer==null){
//            System.out.println("用户为空");
            return ServerResponse.getFail("用户为空");
        }
        int secOrderId = seckillService.getResult(customer.getCustId(),secId);

        return ServerResponse.saveSuccess(secOrderId);
    }
}
